<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息（注意商品名称是唯一的）" type="info" center show-icon></el-alert>
      <el-steps :active="active - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-tabs
        :tab-position="'left'"
        v-model="active"
        :before-leave="beforeTabLeave"
        @tab-click="tabClick"
      >
        <el-tab-pane label="基本信息" name="0">
          <el-form
            :model="addForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="商品名称" prop="goods_name">
              <el-input
                v-model="addForm.goods_name"
                :disabled="step1"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                type="number"
                v-model="addForm.goods_price"
                :disabled="step2"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                type="number"
                v-model="addForm.goods_number"
                autocomplete="off"
                :disabled="step3"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                type="number"
                v-model="addForm.goods_weight"
                autocomplete="off"
                :disabled="step4"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="value"
                :props="cateProps"
                :options="cateList"
                @change="handleChange"
                :disabled="step5"
              ></el-cascader>
            </el-form-item>
          </el-form>
          <el-row>
            <el-button style="float: right" type="success" @click="addnext1"
              >下一步</el-button
            >
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-tag
            :key="tag"
            v-for="tag in canshu"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ New Tag</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form>
            <el-form-item
              v-for="item in shuxing"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            action="https://lianghj.top:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture"
            :headers="headers"
            :on-success="handleSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <el-input
            placeholder="请输入内容"
            v-model="addForm.goods_introduce"
            clearable
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          >
          </el-input>
          <el-button
            type="primary"
            style="margin-top: 100px; float: right"
            @click="add"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :visible.sync="dialogVisible" title="图片预览">
      <img width="100%" :src="previewPath" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      active: "0",
      cateList: [],
      value: [],
      addForm: {
        goods_name: "",
        goods_cat: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      step1: false,
      step2: true,
      step3: true,
      step4: true,
      step5: true,
      count: 2,
      canshu: [],
      inputVisible: false,
      inputValue: "",
      shuxing: [],
      fileList: [],
      headers: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPath: "",
      dialogVisible: false,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    next() {
      //   if (this.active++ > 2) this.active = 0;
      this.active++;
    },
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类数据失败！");
      }
      this.cateList = res.data;
    },
    handleChange(val) {
      console.log(val);
    },
    beforeTabLeave(act, old) {
      // console.log(act,old)
      if (
        this.value.length &&
        !this.step1 &&
        !this.step2 &&
        !this.step3 &&
        !this.step4 &&
        !this.step5
      ) {
        return true;
      } else {
        this.$message.error("请完成基本信息");
        return false;
      }
    },
    addnext1() {
      let c = this.count++;
      console.log(c);
      this.step1 = false;
      if (c == 2 && this.addForm.goods_name) {
        this.step2 = false;
      } else if (c == 3 && this.addForm.goods_price) {
        this.step3 = false;
      } else if (c == 4 && this.addForm.goods_number) {
        this.step4 = false;
      } else if (c == 5 && this.addForm.goods_weight) {
        this.step5 = false;
        this.count = 1;
      } else if (c == 1 && !this.value.length) {
        this.count = c;
        return this.$message.error("输入不能为空");
      } else {
        this.count = c;
        return this.$message.error("输入不能为空");
      }
    },
    async tabClick() {
      if (this.active == "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.value[2]}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("获取动态参数失败");
        }
        this.canshu = res.data[0].attr_vals.length
          ? res.data[0].attr_vals.split(",")
          : [];
      }
      if (this.active == "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.value[2]}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status != 200) {
          return this.$message.error("获取动态参数失败");
        }
        this.shuxing = res.data;
      }
    },
    handleClose(tag) {
      this.canshu.splice(this.canshu.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.canshu.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleRemove(file, fileList) {
      let imageUrl = file.response.data.tmp_path;
      let ind = this.addForm.pics.findIndex((x) => x.pic == imageUrl);
      this.addForm.pics.splice(ind, 1);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.previewPath = file.response.data.url;
    },
    handleSuccess(response, file, fileList) {
      const pic = { pic: response.data.tmp_path };
      this.addForm.pics.push(pic);
      console.log(this.addForm);
    },
    add() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项！");
        }
        this.addForm.goods_cat = this.value.join(",");
        this.addForm.goods_price = Number(this.addForm.goods_price);
        this.addForm.goods_number = Number(this.addForm.goods_number)
        this.addForm.goods_weight = Number(this.addForm.goods_weight)
        console.log(this.addForm);
        const { data: res } = await this.$http.post("goods", this.addForm);
        console.log(res);
        if (res.meta.status != 201) {
          return this.$message.error("添加商品失败，商品名称不唯一或是其他信息有误");
        }
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },
  },
};
</script>
<style scoped>
.el-steps {
  margin: 20px 0px;
}
.el-tag + .el-tag {
  margin: 5px;
}
.button-new-tag {
  margin: 5px;
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  margin: 5px;
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>